<?php
/**
 * Created by PhpStorm.
 * User: wangxiaodan
 * Date: 2017/5/18
 * Time: 下午3:30
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminUsers;
use Illuminate\Support\Facades\Auth;
use Zizaco\Entrust\Entrust;
use App\Models\Children;
use Illuminate\Http\Request;
use App\Models\PrePaidCard;
use Illuminate\Support\Facades\DB;

class CardController extends Controller
{
    public function index(){

        $cards = DB::table('pre_paid_cards')
                ->join('children', 'pre_paid_cards.child_id', '=', 'children.id')
                ->select('*', 'pre_paid_cards.id as card_id', 'pre_paid_cards.created_at as card_time')
                ->latest('pre_paid_cards.created_at')->paginate(config('constants.page_num'));
        return view('admin.cards.index', compact('cards'));
    }

    public function cardList($id){
        $cards = DB::table('pre_paid_cards')
            ->join('children', 'pre_paid_cards.child_id', '=', 'children.id')
            ->select('*', 'pre_paid_cards.id as card_id', 'pre_paid_cards.created_at as card_time')
            ->where("pre_paid_cards.child_id", $id)
            ->latest('pre_paid_cards.created_at')->paginate(config('constants.page_num'));
        return view('admin.cards.index', compact('cards'));
    }

    public function create($id){
        return view('admin.cards.create', compact('id'));
    }

    public function store(Request $request){
        $arr = $request->all();
        $card = new PrePaidCard();
        $card->face_value = $arr['face_value'];
        $card->class_hour = $arr['class_hour'];
        $card->unit_price = $arr['face_value'] / $arr['class_hour'];
        $card->remainder_class_hour = $arr['class_hour'];
        $card->remainder_value = $arr['face_value'];
        $card->child_id = $arr['id'];
        $card->remarks = $arr['remarks'];
        $card->duration = $arr['duration'];

        if ($result = $card->save()){
            $child = Children::find($arr['id']);
            if ($child->status == 0) {
                $child->status = 1;
                $child->save();
            }
            exit(json_encode(array('code'=>1, 'url'=>'/admin/cards')));
        }else{
            exit(json_encode(array('code'=>0, 'msg'=>$result)));
        }
    }

    public function destroy(Request $request, $id){
        if (Auth::guard('admin')->user()->can('delete-card')){
            $card = PrePaidCard::findOrFail($id);
            $child = Children::findOrFail($card->child_id);
            if ($card->delete()){
                add_admin_log("删除".$child->name."的充值卡,面值".$card->face_value.",课时".$card->class_hour, $request);
                exit(json_encode(array('code'=>1)));
            } else {
                exit(json_encode(array('code'=>0, "msg"=>"删除失败")));
            }
        }else{
            exit(json_encode(array('code'=>0, "msg"=>"你没有该权限")));
        }
    }
}